package io.bluerain.service.ui;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.TextView;


import java.util.Timer;
import java.util.TimerTask;

import io.bluerain.service.R;
import io.bluerain.service.service.MyBindService;

public class ServiceTestActivity extends Activity {

    Intent intent;
    Intent bindIntent;
    ServiceConnection connection;
    MyBindService.MyBinder binder;
    TextView text;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.service_test);
        intent = new Intent();
        intent.setAction("io.bluerain.FIRSTSERVICE");
        bindIntent = new Intent();
        bindIntent.setAction("io.bluerain.BINDSERVICE");
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                binder = (MyBindService.MyBinder) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        text = (TextView) findViewById(R.id.txtBinderCount);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0x123) {
                    text.setText(binder.getCount() + "");
                }
            }
        };
    }


    public void startService(View source) {
        startService(intent);
    }


    public void stopService(View source) {
        stopService(intent);
    }

    public void bindService(View source) {
        bindService(bindIntent, connection, Service.BIND_AUTO_CREATE);
    }

    public void unBindService(View source) {

        unbindService(connection);
    }

    public void updateBinder(View source) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0x123);
            }
        }, 0, 200);
    }
}
